package com.yunzheng.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yunzheng.common.BaseResult;
import com.yunzheng.constants.SystemConstants;
import com.yunzheng.dto.*;
import com.yunzheng.entity.ActivityUser;
import com.yunzheng.entity.SysUser;
import com.yunzheng.exception.ServiceException;
import com.yunzheng.redis.RedisManager;
import com.yunzheng.service.SysUserService;
import com.yunzheng.util.TokenParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author Sun
 * @date 2020-07-27 14:33
 */
@Api(tags = "用户管理")
@Slf4j
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private RedisManager redisManager;

    /**
     * 1.根据请求中的token返回当前用户的详细信息
     *
     * /info/showMe -- authc
     *
     * @param request 请求
     * @return 用户详细信息
     */
    @ApiOperation(value = "个人信息：当前登录用户的详细信息")
    @GetMapping("/info/showMe")
    public BaseResult userInfoThis(HttpServletRequest request) {
        return BaseResult.ok(sysUserService.selectInfoById(TokenParser.token2UserId(request)));
    }

    /**
     * 2.根据修改个人的信息
     *
     * /info/change -- authc
     *
     * @param user 用户信息对象
     * @return 操作提示
     */
    @ApiOperation(value = "用户信息：修改当前用户的信息")
    @PutMapping("/info/change")
    public BaseResult userChange(HttpServletRequest request, @Valid @RequestBody UserChangeDTO user) {
        sysUserService.updateInfoById(TokenParser.token2UserId(request), user);
        return BaseResult.ok();
    }

    /**
     * 3.删除当前登录用户账号
     *
     * /removeMe -- authc
     *
     * @param request 请求头
     * @return 操作提示
     */
    @ApiOperation(value = "用户状态：注销当前用户")
    @DeleteMapping("/removeMe")
    public BaseResult userRemove(HttpServletRequest request) {
        // TODO: 2020/8/5 真的需要注销这个操作嘛？或者做成冻结账户。会涉及到文档、项目等
        sysUserService.removeUserById(TokenParser.token2UserId(request));
        redisManager.delete(request.getHeader(SystemConstants.TOKEN));
        return BaseResult.ok();
    }

    /**
     * 4.管理员根据用户ID删除用户
     *
     * /info/remove -- roles[1]
     *
     * @param userId 请求头
     * @return 操作提示
     */
    @ApiOperation(value = "用户信息：管理员根据用户ID删除用户")
    @DeleteMapping("/info/remove")
    public BaseResult userRemove(String userId) {
        sysUserService.removeUserById(userId);
        return BaseResult.ok();
    }

    /**
     * 5.根据用户ID返回用户信息
     *
     * /info/show -- authc
     *
     * @param userId 用户ID
     * @return 用户详细信息
     */
    @ApiOperation(value = "用户信息：查看他人个人信息接口")
    @GetMapping("/info/show")
    public BaseResult userInfo(String userId) {
        return BaseResult.ok(sysUserService.selectInfoById(userId));
    }

    /**
     * 6.禁用某个用户
     *
     * /lock -- roles[1]
     */
    @ApiOperation(value = "禁用用户")
    @PutMapping("/lock")
    public BaseResult lockUser(String userId){
        sysUserService.update(new UpdateWrapper<SysUser>().set(SysUser.COL_USER_STATUS, 1).eq(SysUser.COL_USER_ID, userId));
        log.debug("禁用用户" + userId);
        return BaseResult.ok();
    }

    /**
     * 7.修改用户角色
     * /change/role -- roles[1]
     */
    @ApiOperation(value = "修改用户身份")
    @PutMapping("/change/role")
    public BaseResult updateUserRoles(Integer roleId, String userId){
        if (roleId < 1 || roleId > 2){
            throw new ServiceException("用户身份不合法");
        }
        sysUserService.update(new UpdateWrapper<SysUser>().set(SysUser.COL_USER_IDENTIFY, roleId).eq(SysUser.COL_USER_ID, userId));
        return BaseResult.ok();
    }

    /**
     * 8.修改密码
     *
     * /reset -- authc
     *
     * @param request 请求
     * @return 返回
     */
    @ApiOperation(value = "修改密码")
    @PutMapping("/reset")
    public BaseResult resetPassword(HttpServletRequest request, @Valid @RequestBody PasswordChangeDTO input) {
        sysUserService.changePSW(TokenParser.token2UserId(request), input.getOldPasswd(), input.getNewPasswd());
        return BaseResult.ok();
    }

    /**
     * 获得本用户的角色和权限
     *
     * /role/perm -- authc
     */
    @ApiOperation(value = "获得本用户的角色和权限")
    @GetMapping("/role/perm")
    public BaseResult getUserRolesPerms(HttpServletRequest request){
        String userId = TokenParser.token2UserId(request);
        Subject subject = SecurityUtils.getSubject();
        ActivityUser user = (ActivityUser) subject.getPrincipal();
        if (!user.getUser().getUserId().equals(userId)){
            throw new ServiceException("用户错误,请重试！");
        }
        return BaseResult.ok(user);
    }


    /*
     * 4.发送修改密码用的验证码
     * 给当前登录用户发送验证码
     *
     */
//    @ApiOperation(value = "修改密码：发送手机验证码")
//    @GetMapping("/reset/phone")
//    public BaseResult resetPhone(HttpServletRequest request) {
//        sysUserService.changeVerification(TokenParser.token2UserId(request));
//        return BaseResult.ok();
//    }
}
